using System.Net.WebSockets;
using System.Text;
using System.Text.Json;


namespace WebSMS;


public class WebSocketController : ControllerBase
{
    [HttpGet("/ws")]
    public async Task Get()  
    {  
        if (!HttpContext.WebSockets.IsWebSocketRequest)  
        {  
            HttpContext.Response.StatusCode = 400;  
            return;  
        }  
  
        var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();  
  
        try  
        {  
            var buffer = new byte[1024 * 4]; // 分配一个足够大的缓冲区  
  
            while (webSocket.State == WebSocketState.Open)  
            {  
                var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);  
  
                if (result.MessageType == WebSocketMessageType.Text)  
                {  
                    string text = Encoding.UTF8.GetString(buffer, 0, result.Count);  
  
                    // 在这里处理接收到的文本消息  
                    Console.WriteLine($"Received: {text}");
                    switch (text)
                    {
                        case "ping":
                          await webSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes("pong")), WebSocketMessageType.Text, true, CancellationToken.None);
                            break;
                        case "token":
                            var response = new ResponseObject<string>();
                            var json = JsonSerializer.Serialize(response);
                            await webSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes(json)),
                                WebSocketMessageType.Text, true, CancellationToken.None);
                            break;
                    }
  
                    // 将消息回发给客户端  
                    await webSocket.SendAsync(new ArraySegment<byte>(Encoding.UTF8.GetBytes($"Echo: {text}")), WebSocketMessageType.Text, true, CancellationToken.None);  
                }  
                else if (result.MessageType == WebSocketMessageType.Close)  
                {  
                    await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);  
                    break;  
                }  
  
                // 注意：这里没有处理二进制消息或消息分片的情况  
            }  
        }  
        catch (Exception ex)  
        {  
            Console.WriteLine($"WebSocket error: {ex.Message}");  
  
            // 在这里处理异常，例如关闭WebSocket连接  
            if (webSocket.State == WebSocketState.Open)  
            {  
                await webSocket.CloseAsync(WebSocketCloseStatus.InternalServerError, "An error occurred", CancellationToken.None);  
            }  
        }  
    }  
}